package model;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

public class Servidor implements Runnable {

	private boolean isAtivo;
	private Agencia agencia;

	public Servidor(Agencia agencia) {
		this.agencia = agencia;
	}

	public void desligar() {
		isAtivo = false;
	}

	public void run() {
		System.out.println("Iniciando servidor");
		try {
			ServerSocket sock_in = new ServerSocket(1025);
			sock_in.setSoTimeout(100);
			int id = 0;
			this.isAtivo = true;

			while (this.isAtivo) {
				try {
					Socket socket = sock_in.accept();
					SessaoRemota atd = new SessaoRemota(this.agencia, id++, socket);
					new Thread(atd).start();
				} catch (IOException e) {
					// TODO Auto-generated catch block
				}
			}
			sock_in.close();
		} catch (SocketException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("Encerrando servidor normalmente");
	}
}
